import axios from 'axios'
import {Md5} from "ts-md5";
import {JSEncrypt} from "jsencrypt";
import XEUtils from 'xe-utils'
import type AccountType from "@/api/auth/enums/AccountType";
import type ClientType from "@/api/auth/enums/ClientType"
import type {AxiosRequestConfig} from 'axios'

export interface PasswordCertificationBo {
    md5Salt: string
    rsaPublicKey: string
}

export interface PasswordLoginBo {
    account: string
    password: string,
    accountType: AccountType
    clientType: ClientType
}

export interface InitPasswordBo {
    account: string
    password: string
    accountType: AccountType
}

export function getCertification() {
    return axios.get("/auth/password/certification")
}

export function getImageVerifyCode() {
    return axios.get("/auth/password/imageVerifyCode")
}

function passwordEncode(password: string, certification: PasswordCertificationBo): string {
    const jse = new JSEncrypt();
    jse.setPublicKey(certification.rsaPublicKey);
    return jse.encrypt(Md5.hashStr(password + certification.md5Salt)) as string;
}

export function login(certification: PasswordCertificationBo, data: PasswordLoginBo, config: AxiosRequestConfig) {
    // 设置客户端类型为浏览器
    data = XEUtils.clone(data)
    data.clientType = 1
    data.password = passwordEncode(data.password, certification)
    return axios.post("/auth/password/login", data, config)
}

export function initUserPassword(certification: PasswordCertificationBo, data: InitPasswordBo) {
    // 设置客户端类型为浏览器
    data = XEUtils.clone(data)
    data.password = passwordEncode(data.password, certification)
    return axios.post("/auth/password/initUserPassword", data)
}

/**
 * 重置用户密码为默认密码
 */
export function resetDefaultPassword(data: any) {
    return axios.post("/auth/password/resetDefaultPassword", data);
}

/**
 * 当前用户修改自身密码
 * @param data
 */
export function currUserModifyPassword(certification: any, data: any) {
    data.oldPassword = passwordEncode(data.oldPassword, certification)
    data.newPassword = passwordEncode(data.newPassword, certification)
    return axios.post("/auth/password/currUserModifyPassword", data);
}
